<template>
  <el-card class="search-card">
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" size="default">
      <el-form-item label="任务名称">
        <el-select 
          v-model="searchForm.taskId" 
          placeholder="请选择任务"
          filterable
          clearable
          style="width: 220px;"
        >
          <el-option 
            v-for="item in taskNameOptions" 
            :key="item.id" 
            :label="item.name" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="批次号">
        <el-input v-model="searchForm.batchNo" placeholder="请输入批次号" clearable />
      </el-form-item>
      <el-form-item label="执行状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
          <el-option label="失败" :value="-1" />
          <el-option label="执行中" :value="1" />
          <el-option label="数据对比正常" :value="2" />
          <el-option label="数据对比失败" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineEmits, defineProps } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { getTaskNameList } from '@/api/data-sync';

// 定义组件接收的属性
const props = defineProps({
  initialSearchForm: {
    type: Object,
    default: () => ({
      taskId: '',
      batchNo: '',
      status: null
    })
  }
});

// 定义组件触发的事件
const emit = defineEmits(['search', 'reset']);

// 搜索表单引用
const searchFormRef = ref();

// 搜索表单数据
const searchForm = reactive({
  taskId: props.initialSearchForm.taskId || '',
  batchNo: props.initialSearchForm.batchNo || '',
  status: props.initialSearchForm.status ?? null
});

// 任务名称选项
const taskNameOptions = ref<{id: string, name: string}[]>([]);

// 搜索处理函数
const handleSearch = () => {
  emit('search', { ...searchForm });
};

// 重置处理函数
const handleReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.taskId = '';
  searchForm.batchNo = '';
  searchForm.status = null;
  emit('reset');
};

// 获取任务名称列表
const fetchTaskNames = async () => {
  try {
    const res: any = await getTaskNameList();
    if (res.code === 200) {
      taskNameOptions.value = res.data || [];
    }
  } catch (error) {
    console.error('获取任务名称列表出错:', error);
  }
};

// 组件挂载时获取任务名称列表
onMounted(() => {
  fetchTaskNames();
});
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}
</style>